#include "main.h"

const char *url_escape(const char *url){
	CURL *curl = curl_easy_init();
	int i = 0;
	int before = 0;
	char *back_url = NULL;	
	back_url = static_cast<char *>(malloc(sizeof(char)*strlen(url)));
	strcpy(back_url,url); 
	//最终的URL
	char *final_url = NULL;
	final_url = static_cast<char *>(malloc(sizeof(char)*strlen(url)*2));
	strcpy(final_url,"");

	int count = 1;
	
	while(*back_url++!='\0'){

		if(*back_url !='/'){
			if(i==(int)strlen(url)-1){
				char *part = static_cast<char *>(malloc(sizeof(char)*(i-before)));
				strncpy(part,url+before,strlen(url)-before);
				part[strlen(url)-before] = '\0';
				strcat(final_url,curl_easy_escape(curl,part,0));
			}
		}
		else{
			if(count>2){
				char *part = static_cast<char *>(malloc(sizeof(char)*(i-before+1)));
				strncpy(part,url+before,i-before+1);
				part[i-before+1] = '\0';
				before = i+2;
				strcat(final_url,curl_easy_escape(curl,part,0));
				strcat(final_url,"/");
			}
			else{
				if(count == 2){
					char *header = static_cast<char *>(malloc(sizeof(char)*before+2));
					strncpy(header,url,before+1);
					header[before+1] = '\0';
					strcat(final_url,header);
				}
				before = i+2;
			}
			count++;
		}
		i++;
	}
	//std::cout << "编码后的URL:" << final_url << std::endl;
	return final_url;
}
